import React, { useState, useEffect } from 'react';
import { Form, Input, Select, Checkbox, Button, Upload, message } from 'antd';
// import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { PlusOutlined } from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import { addhourselist, getKeywords, uploadHouseImage } from '../../api/inftan';
import 'antd/dist/reset.css';
import './ReleaseHouse.css'

// 数据选项
const orientedOptions = [
  { label: '东', value: 'ORIEN|141b98bf-1ad0-11e3' },
  { label: '南', value: 'ORIEN|103fb3aa-e8b4-de0e' },
  { label: '西', value: 'ORIEN|61e99445-e95e-7f37' },
  { label: '北', value: 'ORIEN|caa6f80b-b764-c2df' },
  { label: '东南', value: 'ORIEN|dfb1b36b-e0d1-0977' },
  { label: '西南', value: 'ORIEN|2354e89e-3918-9cef' },
  { label: '东北', value: 'ORIEN|67ac2205-7e0f-c057' },
  { label: '西北', value: 'ORIEN|80795f1a-e32f-feb9' },
];

const roomTypeOptions = [
  { label: '一室', value: 'ROOM|d4a692e4-a177-37fd' },
  { label: '二室', value: 'ROOM|d1a00384-5801-d5cd' },
  { label: '三室', value: 'ROOM|20903ae0-c7bc-f2e2' },
  { label: '四室', value: 'ROOM|ce2a5daa-811d-2f49' },
  { label: '四室+', value: 'ROOM|2731c38c-5b19-ff7f' }
];

const cityId = 'AREA|efdb858e-9758-b04d';

const floorOptions = [
  { label: '低层', value: 'FLOOR|3' },
  { label: '中层', value: 'FLOOR|2' },
  { label: '高层', value: 'FLOOR|1' },
];

const supportingOptions = [
  { label: '电视', value: '电视' },
  { label: '冰箱', value: '冰箱' },
  { label: '洗衣机', value: '洗衣机' },
  { label: '空调', value: '空调' },
  { label: '热水器', value: '热水器' },
  { label: '床', value: '床' },
  { label: '暖气', value: '暖气' },
  { label: '宽带', value: '宽带' },
  { label: '衣柜', value: '衣柜' },
  { label: '天然气', value: '天然气' },
];

export default function ReleaseHouse() {
  const [form] = Form.useForm();
  const [uploadedImages, setUploadedImages] = useState([]);
  const [communityOptions, setCommunityOptions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [selectedCommunity, setSelectedCommunity] = useState(null);
  const [editor, setEditor] = useState(null);
  const [descriptionHtml, setDescriptionHtml] = useState('<p>请输入房屋描述...</p>');
  const history = useHistory(); // 使用React Router v5的useHistory
  
  // 处理小区名称搜索
  const handleCommunitySearch = async (value) => {
    setLoading(true);
    setCommunityOptions([]);
    
    if (!value || value.trim().length < 1) {
      setLoading(false);
      return;
    }
    
    try {
      const searchValue = value.trim();
      const params = { name: searchValue };
      const response = await getKeywords(cityId, params);
      
      if (!response) return;
      
      const data = response?.body || response?.data || response || [];
      const options = [];
      
      if (Array.isArray(data)) {
        data.forEach((item) => {
          if (!item) return;
          
          const label = item.streetName;
          const valueField = item.community;
          
          if (label) {
            options.push({
              value: valueField,
              label: label,
              communityInfo: item
            });
          }
        });
      } else if (typeof data === 'object' && data !== null) {
        const label = data.streetName || data.name || data.label || JSON.stringify(data);
        const valueField = data.street || data.id || data.value || JSON.stringify(data);
        
        if (label) {
          options.push({
            value: valueField,
            label: label,
            communityInfo: data
          });
        }
      } else {
        const stringValue = String(data);
        if (stringValue && stringValue !== 'undefined' && stringValue !== 'null') {
          options.push({
            value: stringValue,
            label: stringValue,
            communityInfo: { raw: data }
          });
        }
      }
      
      setCommunityOptions(options);
      
    } catch (error) {
      message.error('搜索小区失败，请重试');
      setCommunityOptions([]);
    } finally {
      setLoading(false);
    }
  };
  
  // 处理小区选择
  const handleCommunityChange = (value, option) => {
    let communityInfo = null;
    
    if (option && option.communityInfo) {
      communityInfo = option.communityInfo;
    } else {
      const selected = communityOptions.find(opt => opt.value === value);
      if (selected) {
        communityInfo = selected.communityInfo;
      }
    }
    
    if (communityInfo) {
      setSelectedCommunity(communityInfo);
    }
  };
  
  // 处理图片上传
  const handleUpload = async ({ file, onSuccess, onError }) => {
    try {
      const formData = new FormData();
      formData.append('file', file);
      
      // 打印调试信息
      console.log('开始上传图片，文件名:', file.name, '大小:', file.size);
      
      // 模拟图片上传成功（备用方案）
      // 如果需要模拟，取消下面的注释并注释掉实际上传的代码
      /*
      setTimeout(() => {
        const mockImagePath = `/uploads/mock_${Date.now()}_${file.name}`;
        const successResult = { 
          status: 'done',
          response: { houseImg: mockImagePath }
        };
        
        onSuccess(successResult);
        
        setUploadedImages(prev => {
          const currentImages = Array.isArray(prev) ? prev : [];
          if (!currentImages.includes(mockImagePath)) {
            return [...currentImages, mockImagePath];
          }
          return currentImages;
        });
        
        message.success('图片上传成功（模拟）');
      }, 500);
      return;
      */
      
      // 实际上传代码
      const res = await uploadHouseImage(formData);
      console.log('上传响应:', res);
      
      // 获取图片路径（兼容不同的响应格式）
      let imagePath = '/uploads/upload_default.png';
      if (res && typeof res === 'string') {
        // 如果响应直接是字符串路径
        imagePath = res;
      } else if (res && res.body) {
        imagePath = Array.isArray(res.body) && res.body.length > 0 ? res.body[0] : res.body;
      } else if (res && res.data && res.data.body) {
        imagePath = Array.isArray(res.data.body) && res.data.body.length > 0 ? res.data.body[0] : res.data.body;
      } else if (res && res.path) {
        imagePath = res.path;
      }
      
      // 确保图片路径格式正确
      if (!imagePath.startsWith('/uploads/')) {
        imagePath = '/uploads/' + imagePath;
      }
      
      // 构建完整的成功结果，包含thumbUrl以确保图片正确预览
      const successResult = { 
        status: 'done',
        response: { houseImg: imagePath },
        thumbUrl: imagePath.startsWith('http') ? imagePath : `http://localhost:8080${imagePath}`
      };
      
      onSuccess(successResult);
      
      // 更新图片列表，避免重复
      setUploadedImages(prev => {
        const currentImages = Array.isArray(prev) ? prev : [];
        if (!currentImages.includes(imagePath)) {
          return [...currentImages, imagePath];
        }
        return currentImages;
      });
      
      message.success('图片上传成功');
    } catch (error) {
      console.error('图片上传错误:', error);
      
      // 错误处理
      let errorMsg = '图片上传失败';
      if (error.response) {
        errorMsg = `上传失败: ${error.response.status} ${error.response.statusText}`;
      } else if (error.request) {
        errorMsg = '网络错误，请检查网络连接';
      } else {
        errorMsg = `上传失败: ${error.message}`;
      }
      
      // 失败时使用本地预览作为备用方案
      const reader = new FileReader();
      reader.onload = (e) => {
        const previewUrl = e.target?.result;
        if (previewUrl) {
          const successResult = { 
            status: 'done',
            response: { houseImg: previewUrl },
            thumbUrl: previewUrl
          };
          onSuccess(successResult);
          
          setUploadedImages(prev => {
            const currentImages = Array.isArray(prev) ? prev : [];
            if (!currentImages.includes(previewUrl)) {
              return [...currentImages, previewUrl];
            }
            return currentImages;
          });
        }
      };
      reader.readAsDataURL(file);
      
      message.error(`${errorMsg}，已使用本地预览`);
    }
  };
  
  // 处理表单提交
  const onFinish = async (values) => {
    console.log('开始提交房源表单，values:', values);
    
    // 处理房屋配置数据
    const supportingStr = Array.isArray(values.supporting) ? values.supporting.join('|') : '';
    
    // 获取有效图片路径（兼容base64预览）
    const validImages = Array.isArray(uploadedImages) ? 
      uploadedImages.filter(img => img && typeof img === 'string') : [];
    
    // 如果有图片且第一个不是默认图片，则使用前几张，否则使用默认图片
    const houseImgStr = validImages.length > 0 ? validImages.slice(0, 9).join('|') : '/uploads/upload_default.png';
    
    // 构建表单数据
    const formData = {
      "title": values.title?.trim() || '默认标题',
      "description": values.description?.trim() || '默认描述',
      "houseImg": houseImgStr,
      "oriented": values.oriented || 'ORIEN|141b98bf-1ad0-11e3',
      "supporting": supportingStr || '床|衣柜',
      "price": values.price?.toString() || '0',
      "roomType": values.roomType || 'ROOM|d4a692e4-a177-37fd',
      "size": values.size?.toString() || '0',
      "floor": values.floor || 'FLOOR|3',
      "community": values.community || "AREA|93cbbe43-741d-de54" // 使用用户选择的小区
    };
    
    // 打印提交的数据用于调试
    console.log('提交的表单数据:', formData);
    
    // 检查必填字段
    const requiredFields = ['title', 'price', 'size', 'community', 'roomType', 'floor', 'oriented'];
    const missingFields = requiredFields.filter(field => !formData[field]);
    
    if (missingFields.length > 0) {
      message.warning(`部分信息缺失: ${missingFields.join(', ')}，但将继续提交`);
    }
    
    try {
      // 检查token是否存在
      const token = localStorage.getItem('token');
      if (!token) {
        message.warning('未登录，将使用模拟提交');
        // 模拟成功提交
        message.success('房屋发布成功！(模拟)');
        
        // 重置表单和状态
        form.resetFields();
        setUploadedImages([]);
        setSelectedCommunity(null);
        return;
      }
      
      // 调用发布房源接口
      console.log('调用发布房源接口...');
      const result = await addhourselist(formData);
      console.log('发布房源结果:', result);
      
      message.success('房屋发布成功！');
      
      // 重置表单和状态
      form.resetFields();
      setUploadedImages([]);
      setSelectedCommunity(null);
    } catch (error) {
      // 错误处理
      console.error('发布房源错误:', error);
      
      let errorMsg = '房屋发布失败，请重试！';
      const errorWithResponse = error as { response?: { status: number; data?: { description?: string } }; request?: any; message?: string };
      
      if (errorWithResponse.response) {
        console.log('错误响应:', errorWithResponse.response);
        if (errorWithResponse.response.status === 400) {
          if (errorWithResponse.response.data && errorWithResponse.response.data.description === 'token异常或者过期') {
            localStorage.removeItem('token');
            localStorage.removeItem('username');
            errorMsg = '登录已过期，请重新登录！';
            setTimeout(() => {
          history.push('/login');
        }, 1500);
          } else if (errorWithResponse.response.data && errorWithResponse.response.data.description) {
            errorMsg = errorWithResponse.response.data.description;
          }
        } else if (errorWithResponse.response.status === 401) {
          errorMsg = '未授权，请重新登录！';
        } else if (errorWithResponse.response.status === 403) {
          errorMsg = '没有权限发布房源！';
        } else if (errorWithResponse.response.status === 404) {
          errorMsg = '请求的资源不存在！';
        } else if (errorWithResponse.response.status >= 500) {
          errorMsg = '服务器错误，请稍后重试！';
        }
      } else if (errorWithResponse.request) {
        errorMsg = '网络错误，请检查网络连接！';
      } else if (errorWithResponse.message) {
        errorMsg = errorWithResponse.message;
      }
      
      message.error(errorMsg);
    }
  };
  
  // 处理图片删除
  const handleRemove = (file) => {
    let imageToRemove = '';
    
    // 从不同来源获取图片路径
    if (file.response && typeof file.response === 'object' && file.response.houseImg) {
      imageToRemove = file.response.houseImg;
    } else if (file.response && typeof file.response === 'string') {
      imageToRemove = file.response;
    } else if (file.url) {
      imageToRemove = file.url;
    } else if (file.name) {
      imageToRemove = file.name;
    }
    
    // 过滤图片列表
    const newImages = uploadedImages.filter(img => {
      if (imageToRemove && imageToRemove.includes('/uploads/')) {
        return img !== imageToRemove;
      }
      return !img.endsWith(imageToRemove);
    });
    
    setUploadedImages(newImages);
    return true;
  };
  
  // 自定义上传按钮
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传房屋图片</div>
    </div>
  );

  // 及时销毁 editor
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  return (
    <div className="release-house-container">
      <Form
        form={form}
        layout="horizontal"
        onFinish={onFinish}
        className="release-house-form"
        initialValues={{
          supporting: [],
        }}
        colon={false}
      >
        {/* 第一行：小区名称、租金、面积 */}
        <div className="form-row-3">
          <Form.Item
            name="community"
            label="小区名称"
            rules={[{ required: true, message: '请搜索并选择小区名称' }]}
            className="form-item-3"
          >
            <Select
              placeholder="请搜索小区名称"
              showSearch
              filterOption={false}
              optionFilterProp="label"
              remote="true"
              loading={loading}
              onChange={handleCommunityChange}
              notFoundContent={loading ? '搜索中...' : '未找到相关小区'}
              allowClear
              style={{ width: '100%' }}
              onSearch={handleCommunitySearch}
              defaultActiveFirstOption={false}
              autoClearSearchValue={false}
              tokenSeparators={[',', ' ']}
            >
              {communityOptions.map((option) => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="price"
            label="租金"
            rules={[{ required: true, message: '请输入租金' }]}
            className="form-item-3"
          >
            <Input placeholder="请输入租金" />
          </Form.Item>
          
          <Form.Item
            name="size"
            label="面积"
            rules={[{ required: true, message: '请输入建筑面积' }]}
            className="form-item-3"
          >
            <Input placeholder="请输入建筑面积" />
          </Form.Item>
        </div>
        
        {/* 第二行：所在楼层、户型、朝向 */}
        <div className="form-row-3">
          <Form.Item
            name="floor"
            label="所在楼层"
            rules={[{ required: true, message: '请选择所在楼层' }]}
            className="form-item-3"
          >
            <Select placeholder="请选择所在楼层">
              {floorOptions.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="roomType"
            label="户型"
            rules={[{ required: true, message: '请选择户型' }]}
            className="form-item-3"
          >
            <Select placeholder="请选择户型">
              {roomTypeOptions.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="oriented"
            label="朝向"
            rules={[{ required: true, message: '请选择朝向' }]}
            className="form-item-3"
          >
            <Select placeholder="请选择朝向">
              {orientedOptions.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </div>
        
        {/* 房屋配置 */}
        <Form.Item
          name="supporting"
          label="房屋配置"
          rules={[{ required: true, message: '请至少选择一项' }]}
          className="full-width-item"
        >
          <div className="supporting-options">
            <Checkbox.Group>
              {supportingOptions.map(option => (
                <Checkbox key={option.value} value={option.value}>
                  {option.label}
                </Checkbox>
              ))}
            </Checkbox.Group>
          </div>
        </Form.Item>
        
        {/* 房屋标题 */}
        <Form.Item
          name="title"
          label="标题"
          rules={[{ required: true, message: '请输入房屋标题' }]}
        >
          <Input placeholder="请输入标题(例如: 整租小区名2室2000元)" />
        </Form.Item>

        {/* 图片上传 */}
        <Form.Item
          name="houseImg"
          label="上传图片"
        >
          <Upload
            customRequest={handleUpload}
            listType="picture-card"
            fileList={uploadedImages.map((img, index) => ({ uid: index, name: img.split('/').pop() || `image-${index}`,
                url: `http://localhost:8080${img}` }))}
            onRemove={handleRemove}
            multiple
            accept="image/*"
            showUploadList
            beforeUpload={(file) => {
              // 检查文件类型
              const isImage = file.type.startsWith('image/');
              if (!isImage) {
                message.error('请上传图片文件!');
                return Upload.LIST_IGNORE;
              }
              // 检查文件大小（10MB）
              const isLt10M = file.size / 1024 / 1024 < 10;
              if (!isLt10M) {
                message.error('图片大小不能超过10MB!');
                return Upload.LIST_IGNORE;
              }
              return true; // 返回true让customRequest处理上传
            }}
          >
            {uploadButton}
          </Upload>
        </Form.Item>
        
        {/* 房屋描述 - 富文本编辑器 */}
        <Form.Item
          name="description"
          label="房屋描述"
          rules={[{ required: true, message: '请输入房屋描述' }]}
          className="full-width-item"
          initialValue="<p>请输入房屋描述...</p>"
        >
          <div >
            <textarea name="" id="" className='texts'></textarea>
          
          </div>
        </Form.Item>
        
        {/* 提交按钮 */}
        <Form.Item className="full-width-item form-submit">
          <Button type="primary" htmlType="submit" size="large">
            发布房源
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}